#include "HttpUtils.h"
#include "Constants.h"
#include <iostream>
#include <sstream>
#include <QString>
#include <QDebug>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkInterface>
#include <QList>
#include <QObject>

HttpUtils::HttpUtils(){
}

void HttpUtils::requestUrl(int eventId, QUrl url, IQtHttpRespEventHandler *handler, QObject *receiver){
    if(!checkConnectionState()){
        handler->handleNetworkErrorEvent();
        return;
    }

    QNetworkRequest request;
    std::stringstream ss;
    ss<<eventId;
    url.addQueryItem(QString(EVENT_ID_KEY),QString(ss.str().c_str()));
    request.setUrl(url);
    QNetworkAccessManager* manager=new QNetworkAccessManager(receiver);
    QObject::connect(manager,SIGNAL(finished(QNetworkReply*)),receiver,SLOT(handleOriginRespSucceedEvent(QNetworkReply*)));
    QNetworkReply* reply=manager->get(request);
    QObject::connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),receiver,SLOT(handleOriginRespErrorEvent(QNetworkReply::NetworkError)));

}

bool HttpUtils::checkConnectionState(){
    QList<QNetworkInterface> interfaces=QNetworkInterface::allInterfaces();
    bool connected=false;
    for(int i=0;i<interfaces.count();i++){
        QNetworkInterface interface=interfaces[i];
        if(interface.isValid()&&!interface.flags().testFlag(QNetworkInterface::IsLoopBack)
                &&interface.flags().testFlag(QNetworkInterface::IsRunning)){
            qDebug()<<QString(QObject::tr("Connected to the network through %1")).arg(interface.humanReadableName());
            connected=true;
            break;
        }
    }

    return connected;
}
